package com.rongshu.sendmessage.util.upData;

import android.annotation.SuppressLint;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.core.content.FileProvider;

import com.rongshu.sendmessage.R;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import static android.content.Context.BIND_AUTO_CREATE;

public class UpdateManager {
    /* 下载中 */
    private final int DOWNLOAD = 1;
    /* 下载结束 */
    private final int DOWNLOAD_FINISH = 2;
    /* 不是最新版本 */
    private final int NoNewAPK = 3;
    /* 是最新版本 */
    private final int YESNewAPK = 4;
    protected final int MUST_APK = 12;
    protected final int DISSMISS = 13;
    private final String url;
    /* 下载保存路径 */
    private String mSavePath;
    /* 记录进度条数量 */
    private int progress;
    /* 是否取消更新 */
    private boolean cancelUpdate = false;
    private Context mContext;
    /* 更新进度条 */
    private ProgressBar mProgress;
    private Dialog mDownloadDialog;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            try{
                switch (msg.what) {
                    // 正在下载
                    case DOWNLOAD:
                        // 设置进度条位置
                        mProgress.setProgress(progress);
                        break;
                    case DISSMISS:
                        // guanbis
                        // 取消下载对话框显示
                        mDownloadDialog.dismiss();
                        if (activty!=null)
                            activty.finishApp();
                        break;
                    case DOWNLOAD_FINISH:
                        // 安装文件
                        mDownloadDialog.dismiss();

                        installApk();
                        break;
                    case YESNewAPK:
                        break;
                    default:
                        break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        };
    };
    private MustApk activty;
    public UpdateManager(Context context, Context activty, String url) {
        this.mContext = context;
        if (activty instanceof MustApk)
            this.activty = (MustApk) activty;
        this.url=url;
        String sdpath = Environment.getExternalStorageDirectory()
                + "/";
        mSavePath = sdpath + "download";
    }
    /**
     * 检测软件更新
     */
    public void checkUpdate() {
        showDownloadDialog();
    }
    /**
     * 显示软件下载对话框
     */
    private void showDownloadDialog() {
        // 构造软件下载对话框
        Builder builder = new Builder(mContext);
        // 给下载对话框增加进度条
        final LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.update_progress, null);
        mProgress = (ProgressBar) v.findViewById(R.id.update_progress);
        builder.setView(v);
        // 取消更新
        builder.setNegativeButton("取消更新", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                // 设置取消状态
                cancelUpdate = true;
            }
        });
        mDownloadDialog = builder.create();
        mDownloadDialog.setOnKeyListener(new OnKeyListener() {
            //第一个参数是拦截到此事件的对话框对象的引用,第二个参数是此事件对应的keyCode,第三个参数是此事件对象本身。
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                // TODO Auto-generated method stub
                if(keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount()==0)
                {
                    System.out.println("000000");
//	            dialog.dismiss();
                }
                return true;
            }
        });
        mDownloadDialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失
        mDownloadDialog.show();
//        Intent service = new Intent(mContext,UpdateService.class);
//        service.putExtra("dawn_url",url);
////                mContext.startService(service);*
//        isBindService = mContext.bindService(service, conn, BIND_AUTO_CREATE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
            Intent service = new Intent(mContext, UpdateService.class);
            service.putExtra("dawn_url",url);
//                mContext.startService(service);*
            isBindService = mContext.bindService(service, conn, BIND_AUTO_CREATE);
        }else {
            downloadApk();
        }
    }

    private boolean isBindService;
    private ServiceConnection conn = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            UpdateService.DownloadBinder binder = (UpdateService.DownloadBinder) service;
            UpdateService downloadService = binder.getService();
            //接口回调，下载进度
            downloadService.setOnProgressListener(new UpdateService.OnProgressListener() {
                @Override
                public void onProgress(float fraction) {
                    Log.i("DOMNG", "下载进度：" + fraction);
                    progress = (int)(fraction * 100);
                    // 更新进度
                    mHandler.sendEmptyMessage(DOWNLOAD);
                    if (fraction == UpdateService.UNBIND_SERVICE && isBindService) {
                        mContext.unbindService(conn);
                        isBindService = false;

                        MustApk mustApk = activty;
                        if (mustApk!=null)
                            mustApk.finishApp();
                    }
                }
            });
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };
    /**
     * 下载apk文件
     */
    private void downloadApk() {
        // 启动新线程下载软件
        Log.d("dong","downloadApk");
        new downloadApkThread().start();
    }

    /**
     * 下载文件线程
     */
    private class downloadApkThread extends Thread {
        @Override
        public void run() {
            try {
                // 判断SD卡是否存在，并且是否具有读写权限
                Log.d("DONG","Environment.MEDIA_MOUNTED))");
                if (Environment.getExternalStorageState().equals(
                        Environment.MEDIA_MOUNTED)) {
                    // 获得存储卡的路径


                    URL url = new URL(UpdateManager.this.url);//、、"http://issuecdn.baidupcs.com/issue/netdisk/apk/BaiduNetdisk_7.15.1.apk"

                    // 创建连接
                    HttpURLConnection conn = (HttpURLConnection) url
                            .openConnection();

                    conn.connect();
                    // 获取文件大小
                    int length = conn.getContentLength();
                    // 创建输入流
                    InputStream is = conn.getInputStream();
                    Log.d("DONG","is");
                    File file = new File(mSavePath);
                    // 判断文件目录是否存在
                    if (!file.exists()) {
                        file.mkdir();
                    }
                    File apkFile = new File(mSavePath, "huoyunbao"
                            + ".apk");
                    FileOutputStream fos = new FileOutputStream(apkFile);
                    int count = 0;
                    // 缓存
                    byte buf[] = new byte[1024];
                    // 写入到文件中
                    do {
                        int numread = is.read(buf);
                        count += numread;
                        // 计算进度条位置
                        progress = (int) (((float) count / length) * 100);
                        // 更新进度
                        mHandler.sendEmptyMessage(DOWNLOAD);
                        if (numread <= 0) {
                            // 下载完成
                            mHandler.sendEmptyMessage(DOWNLOAD_FINISH);
                            break;
                        }
                        // 写入文件
                        fos.write(buf, 0, numread);
                    } while (!cancelUpdate);// 点击取消就停止下载.
                    fos.close();
                    is.close();
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();

            } catch (Exception e) {
                e.printStackTrace();

            }

            mHandler.sendEmptyMessage(DISSMISS);
        }
    }

    /**
     * 安装APK文件
     */
    private void installApk() {
        try{
            File apkFile = new File(mSavePath, "tianjin_yiyuan" + ".apk");
            if (!apkFile.exists()) {
                return;
            }
            // 通过Intent安装APK文件
            Intent intent = new Intent(Intent.ACTION_VIEW);

            //兼容7.0
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                Uri contentUri = FileProvider.getUriForFile(mContext, mContext.getPackageName() + ".fileProvider", apkFile);
                intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
                //兼容8.0
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    boolean hasInstallPermission = mContext.getPackageManager().canRequestPackageInstalls();
                    if (!hasInstallPermission) {
                        Toast.makeText(mContext,"请允许未知应用安装！",Toast.LENGTH_LONG).show();
                        startInstallPermissionSettingActivity();
                        return;
                    }
                }
            } else {
                intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            }
            if (mContext.getPackageManager().queryIntentActivities(intent, 0).size() > 0) {
                mContext.startActivity(intent);
            }
            if (activty!=null)
                activty.finishApp();
        } catch (Exception e) {
            e.printStackTrace();

        }
    }
    /**
     * 跳转到设置-允许安装未知来源-页面
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    private void startInstallPermissionSettingActivity() {
        //注意这个是8.0新API
        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        mContext.startActivity(intent);
    }
    public interface MustApk{

        void finishApp();
    }

}
